import axios, { AxiosRequestHeaders } from 'axios'
import { useLoginInfoStore } from '@/store'
import { ElMessageBox } from 'element-plus'

/**
 * 创建请求
 * @param axiosConfig - axios配置，后续可继续优化
 */
export function createRequest(axiosConfig: any) {
  const instance = axios.create(axiosConfig)
  instance.interceptors.request.use(
    (config) => {
      ;(config.headers as AxiosRequestHeaders).SERVICE_TOKEN = useLoginInfoStore().loginInfo.token
      ;(config.headers as AxiosRequestHeaders).USER_TOKEN = 'app'
      return config
    },
    (error) => {
      return Promise.reject(error)
    }
  )
  instance.interceptors.response.use(
    (response) => {
      //token超时处理
      if (response?.data?.message === 'EXPIRED') {
        ElMessageBox.confirm('登录信息已失效，请重新登录', {
          showClose: false,
          showCancelButton: false,
          closeOnClickModal: false,
          closeOnPressEscape: false,
          confirmButtonText: '确认',
          type: 'warning',
        })
          .then(() => {
            if (useLoginInfoStore().loginInfo.loginType === 2) {
              return (window.location.href = '/userLogin')
            }
            window.location.href = '/'
          })
          .catch(() => {
            // catch error
          })
      }
      const res = response.data
      return res
    },
    (error) => {
      window.$notification?.error({
        content: '错误',
        meta: error?.response?.data?.data,
        duration: 3000,
      })
      return Promise.reject(error)
    }
  )
  return instance
}
